<template>
  <div>

    <a-modal :visible="modalVisable" title="分时数据" @ok="cancelModal" @cancel="cancelModal" :width="modelWidth">
      <template #footer>

      </template>
      <div style="padding:20px;position: relative;">
        <Spin tip="Loading..." :style="{position: 'absolute', top: topPercent, left:'45%'}" :spinning="showLoading" />
        <div id="hourChart" :style="{width: '100%', height: modelHeight}"></div>
      </div>
    </a-modal>
  </div>
</template>

<script lang="ts">
import { Modal } from 'ant-design-vue';
export default {
  components: {
    AModal: Modal
  },
};
</script>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import { Spin } from 'ant-design-vue'
import { init, dispose } from 'klinecharts';
import { fetchKlineDataHr2 } from '/@/api/stock/klineDataDao';
import { decode } from '../../utils/sf_sdk';
const modalVisable = ref(false);
const stockData = ref({});
const chartView = ref();
const showLoading = ref(false);
const topPercent = ref('40%');
const modelWidth = ref(1200);
const modelHeight = ref('450px');
const zoomScale = ref(0.5);

function cancelModal() {
  dispose('hourChart');
  modalVisable.value = false;
}

function showModal(data) {
  showLoading.value = true;
  stockData.value = data;
  modalVisable.value = true;
  nextTick(() => {
    showChartView();
  });
};
function pad(num) {
  return num.toString().padStart(2, "0");
}
function dateFormat(data) {
  if (data && data.length > 0) {
    let first = data[0];
    let date = first.date;
    let year = date.getFullYear();
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let fullDate = `${year}-${pad(month)}-${pad(day)}`;
    first.date = fullDate;
  }
}
function dateTimeFormat(date) {
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  let day = date.getDate();
  let hour = date.getHours();
  let minute = date.getMinutes();
  return `${year}-${pad(month)}-${pad(day)} ${pad(hour)}:${pad(minute)}:00`;
}

function convert2KlineData(originalData) {
  let size = originalData.length;
  let klineDatas = [];
  for (var i = 0; i < size; i++) {
    let cdata = originalData[i];
    let data = {
      'stockCode': stockData.value.data.stockCode,
      'stockName': stockData.value.data.stockName,
      'high': cdata.price,
      'low': cdata.price,
      'open': cdata.price,
      'close': cdata.price,
      'volumn': cdata.volumn,
      'timestamp': cdata.date,
      'riseAndFall': cdata.riseAndFall
    }
    klineDatas.push(data);
  }
  return klineDatas;
}

function fillMinuteData(originalData) {
  let startTime = new Date(originalData[0].date + ' 09:30:00');
  let size = originalData.length;
  let preclose = originalData[0].prevclose;
  for (var i = 1; i < size; i++) {
    let data = originalData[i];
    let step = i == 121 ? 91 : 1;
    startTime.setMinutes(startTime.getMinutes() + step);
    data.date = dateTimeFormat(startTime);
    let riseAndFall = (data.price - preclose)*100 / preclose;
    data.riseAndFall = riseAndFall.toFixed(2);
  }
  originalData.splice(0, 1);
  originalData.splice(originalData.length - 2, 2);
}

function filterTargetDateData(decodeHars) {
  let date = stockData.value.data.timestamp.substring(0, 10);
  let matchedData = null;
  for (var i = 0; i < decodeHars.length; i++) {
    let data = decodeHars[i];
    let dt = data[0].date;
    if (dt.indexOf(date) == 0) {
      matchedData = data;
      break;
    }
  }
  if (matchedData) {
    fillMinuteData(matchedData);
    let klineDatas = convert2KlineData(matchedData);
    chartView.value.applyNewData(klineDatas);
  }
  showLoading.value = false;
}
/**
 * 
 * @param decodeHars 
 */
function showHourLineData(decodeHars) {
  if (decodeHars.length > 0) {
    filterTargetDateData(decodeHars);
  }
}

function showChartView() {
  chartView.value = init('hourChart');
  chartView.value.setStyles({
    candle: {
      type: 'area',
      tooltip: {
        custom: ({ current }: { current: any }) => {
          return [
            { title: "时间：", value: "{time}" },
            { title: "价格：", value: "{open}" },
            { title: "涨跌幅：", value: current.riseAndFall + "%" }
          ];
        },
      }
    },
  });
  chartView.value?.zoomAtDataIndex(zoomScale.value, 0);
  let stockCode = stockData.value.data.stockCode;
  let date = stockData.value.data.timestamp.substring(0, 10);
  let ym = date.substring(0, 7).replace('-', '_');
  let exchange = 'sz';
  if (stockCode.indexOf('000') == 0 || stockCode.indexOf('001') == 0) {
    exchange = 'sz';
  } else if (stockCode.indexOf('688') == 0 || stockCode.indexOf('600') == 0 || stockCode.indexOf('60')==0) {
    exchange = 'sh'
  } else if (stockCode.indexOf('82') == 0 || stockCode.indexOf('83') == 0
    || stockCode.indexOf('87') == 0 || stockCode.indexOf('88') == 0
    || stockCode.indexOf('43') == 0) {
    exchange = 'bj'
  }
  fetchKlineDataHr2({
    'stockCode': exchange + stockCode,
    'date': date
  }).then(data => {
    let regex = `MLC_${exchange}${stockCode}_${ym}="(.+?)".+`;
    const regExp = new RegExp(regex, 'g');
    const results = regExp.exec(data);
    let decodeHars = [];
    if (results && results.length > 0) {
      let result = results[1];
      let har = result.split(',');
      for (var i = 0; i < har.length; i++) {
        let decodeHa = decode(har[i]);
        dateFormat(decodeHa);
        decodeHars.push(decodeHa);
      }
    }
    showHourLineData(decodeHars);
  })
}

onMounted(() => {
  var w = window.innerWidth;
  if(w<1420){
    topPercent.value = '34%';
    modelWidth.value = 1000;
    modelHeight.value='400px';
    zoomScale.value = 0.4
  } 
  if(w<1300){
    topPercent.value = '28%';
    modelWidth.value = 860;
    modelHeight.value='360px';
    zoomScale.value = 0.38
  }
  if(w<1200){
    topPercent.value = '28%'
    modelWidth.value = 800;
    modelHeight.value='340px';
    zoomScale.value = 0.32
  }
});

onUnmounted(() => {

});

defineExpose({ showModal });

</script>

<style scoped></style>